/*
 * Copyright 2021-2030 itbox.cn All right reserved. This software is the confidential and proprietary information
 * of itbox.cn ("Confidential Information"). You shall not disclose such Confidential Information and shall use it
 * only in accordance with the terms of the license agreement you entered into with itbox.cn.
 */
package cn.itbox.example.application.service.impl;

import cn.itbox.example.application.facotry.RoleFactory;
import cn.itbox.example.domain.event.role.RoleCreateEvent;
import cn.itbox.example.domain.event.role.RoleDeleteEvent;
import cn.itbox.example.domain.event.role.RoleUpdateEvent;
import cn.itbox.example.domain.repository.RoleRepository;
import cn.itbox.example.application.service.RoleCommandService;
import cn.itbox.uap.domain.event.publish.DomainEventPublisher;
import cn.itbox.example.model.request.CreateRoleRequest;
import cn.itbox.example.model.request.UpdateRoleRequest;
import cn.itbox.example.domain.model.RoleModel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @BelongProject springboot-study
 * @BelongPackage cn.itbox.example.application.service.impl
 * @Description TODO
 * @ClassName RoleCommandServiceImpl
 * @Author xingc
 * @Date 2023/11/26 23:14
 * @Version 1.0.0
 */
@Slf4j
@Service
public class RoleCommandServiceImpl implements RoleCommandService {
    @Resource
    private RoleRepository roleRepository;

    @Autowired
    private DomainEventPublisher domainEventPublisher;

    @Override
    public Long create(CreateRoleRequest request) {
        // 创建角色
        RoleModel model = RoleFactory.createRole(request);

        // 保存角色
        //RoleModel savedModel = model.save();
        roleRepository.save(model);

        // 发布事件
        domainEventPublisher.publishEvent(new RoleCreateEvent(model));

        return model.getId();
    }

    @Override
    public void update(UpdateRoleRequest request) {
        // 创建角色
        RoleModel model = RoleFactory.updateRole(request);

        // 保存角色
        //RoleModel save = model.save();
        roleRepository.save(model);

        // 发布事件
        domainEventPublisher.publishEvent(new RoleUpdateEvent(model));
    }

    @Override
    public void delete(Long id) {
        // 创建角色
        RoleModel model =  RoleFactory.byId(id);

        // 删除角色
        //model.delete();
        roleRepository.delete(id);

        // 发布事件
        domainEventPublisher.publishEvent(new RoleDeleteEvent(id));
    }
}
